package com.apobates.jforum.grief.schema2doc.output.docx;

import com.apobates.jforum.grief.schema2doc.core.SchemaOutput;
import com.apobates.jforum.grief.schema2doc.core.entity.Information;
import com.apobates.jforum.grief.schema2doc.core.entity.Table;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import java.io.File;
import java.io.IOException;
import java.util.stream.Stream;

/**
 * Word文件输出
 * 使用docx4j
 */
public class DocxWordOutput extends AbstractDocxWordOutput implements SchemaOutput {
    private final String outputPath;
    private int total = 0;
    public DocxWordOutput(String outputPath) {
        this.outputPath = outputPath;
    }

    @Override
    public int flush(Information information, Stream<Table> tables) throws IOException {

        try {
            WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
            MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
            // mainDocumentPart.addStyledParagraphOfText("Title", "Hello World!");
            // mainDocumentPart.addParagraphOfText("Welcome To Baeldung");
            tables.forEach(table -> {
                addElement(mainDocumentPart, table);
                total+=1;
            });
            String outputFilePath = String.format("%s/%d.docx", outputPath, System.currentTimeMillis());
            File exportFile = new File(outputFilePath);
            wordPackage.save(exportFile);
            return total;
        }catch (Docx4JException e){
            throw new IOException(e);
        }

    }

    @Override
    public int getWriteSize() {
        return total;
    }

}
